<template>
<div>
    <div class="search">
        <input v-model="keyword" class="searchInput" type="text" placeholder="输入城市名或拼音">
    </div>
    <div class="search-content" ref="search" v-show="keyword">
        <ul>
            <li class="search-item" v-for="(item,index) in list" :key="index" @click="btnCityClick">
                {{item}}
            </li>
            <li class="search-item" v-show="hasNoData">
                没有找到匹配数据
            </li>
        </ul>
    </div>
</div>
</template>

<script>
import Bscroll from 'better-scroll'
import {mapMutations} from 'vuex'
export default {
    name: 'CitySearch',
    props: {
        cities: Array,
    },
    data() {
        return {
            keyword: '',
            list: [],
            timer: null,
        }
    },
    methods: {
        btnCityClick(e) {
            // console.log(e)
            // this.$store.dispatch('changCity',e.target.innerText)
            // this.$store.commit('changeCity', e.target.innerText)
            // console.log(e)
            this.$router.push('/')
            this.changeCity(e.target.innerText)
        },
        ...mapMutations(['changeCity'])

    },
    watch: {
        keyword() {
            if (this.timer) {
                clearTimeout(this.timer)
            }
            this.timer = setTimeout(() => {
                const result = [];
                for (let i in this.cities) {
                    this.cities[i].lists.forEach((index) => {
                        if (this.keyword) {
                            if (index.indexOf(this.keyword) > -1) {
                                result.push(index)
                            } else {
                                this.list = [];
                            }
                        }
                    })
                    this.list = result;
                }
            }, 100)
        }
    },
    computed: {
        hasNoData() {
            return !this.list.length;
        }
    },
    mounted() {
        this.scroll = new Bscroll(this.$refs.search, {
            click: true,
        })
    }
}
</script>

<style scoped>
.search {
    height: 1.7rem;
    padding: 0 .5rem .3rem 0;
    background-color: #00bcd4;
}

.searchInput {
    width: 100%;
    height: 1.5rem;
    line-height: 1.5rem;
    text-align: center;
    border-radius: .3rem;
    padding: 0 .1rem;
}

.search-content {
    position: absolute;
    z-index: 1;
    overflow: hidden;
    top: 5rem;
    left: 0;
    right: 0;
    bottom: 0;
    background-color: #eee;
}

.search-item {
    line-height: 1.8rem;
    padding-left: .4rem;
    background-color: #fff;
    color: #666;
    border-bottom: 1px solid #ccc
}
</style>
